<?php

namespace app\common\model;

use think\Db;
use think\Exception;
use think\Model;

class OrderTbk extends Model
{
    // 表名
    protected $name = 'order_tbk';
    
    // 自动写入时间戳字段
    protected $autoWriteTimestamp = false;

    // 定义时间戳字段名
    protected $createTime = false;
    protected $updateTime = false;
    
    // 追加属性
    protected $append = [
        'createTime_text',
        'earningTime_text',
	    'status_text',
	    'pay_status_text'
    ];
    

    const STATUS_W = 0;
    const STATUS_S = 1;
	CONST STATUS_F = 2;
    const STATUS_N = 3;
    const STATUS_P = 4;
    
    public static $statusList = [
        self::STATUS_W => '待结算',
	    self::STATUS_S => '待返利',
	    self::STATUS_F => '已返利',
	    self::STATUS_N =>  '匹配用户出错',
	    self::STATUS_P =>  '待匹配',
    ];
    
    
    public function getStatusTextAttr($value, $data) {
    	$value = $value ? $value : $data['status'];
    	$list = self::$statusList;
    	return isset($list[$value]) ? $list[$value] : '';
    }
    
	CONST PAY_STATUS_3 = 3;
	CONST PAY_STATUS_12 = 12;
	CONST PAY_STATUS_13 = 13;
	CONST PAY_STATUS_14 = 14;
	
	public static $payStatusList = [
		self::PAY_STATUS_3 => '订单结算',
		self::PAY_STATUS_12 => '订单付款',
		self::PAY_STATUS_13 => '订单失效',
		self::PAY_STATUS_14 => '订单成功',
	];
	
	public function getPayStatusTextAttr($value, $data) {
		$value = $value ? $value : $data['payStatus'];
		$list = self::$payStatusList;
		return isset($list[$value]) ? $list[$value] : '';
	}

    public function getCreatetimeTextAttr($value, $data)
    {
        $value = $value ? $value : $data['createTime'];
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }


    public function getEarningtimeTextAttr($value, $data)
    {
        $value = $value ? $value : $data['earningTime'];
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }

    protected function setCreatetimeAttr($value)
    {
        return $value && !is_numeric($value) ? strtotime($value) : $value;
    }

    protected function setEarningtimeAttr($value)
    {
        return $value && !is_numeric($value) ? strtotime($value) : $value;
    }
	
	
	/**
	 * 淘宝客佣金返利
	 * @param $order 订单信息
	 * @param $config 返利配置
	 * @return bool
	 * @throws \think\exception\PDOException
	 */
	public function rebate($order){
		$this->startTrans();
		$recordModel = new CouponCollectRecord();
		try {
			
			//更改淘宝客订单返利状态
			$tbkRes = $this->where(['id' => $order['id']])
				->update([
					'status' => self::STATUS_F
				]);
			if(!$tbkRes) {
				throw new Exception('更改淘宝客订单返利状态出错');
			}
			
			//更改领券记录状态
			$recordRes = $recordModel
				->where(['id' => $order['record_id']])
				->update([
					'status' => $recordModel::STATUS_Y
				]);
			if(!$recordRes) {
				throw new Exception('更改领取记录状态出错');
			}
			
			//查找已经生成的待返利记录
			$rebateModel = new RebateRecord();
			$rebateRes = $rebateModel->rebate($order['taobaoTradeParentId'], $rebateModel::TYPE_TBK);
			if(!$rebateRes) {
				throw new Exception($rebateModel->getError());
			}
			
			$this->commit();
			return $order['id'].'返利成功'.PHP_EOL;
			
		} catch (Exception $e) {
			$this->rollback();
			return $order['id'].'返利出错：'.$e->getMessage().PHP_EOL;
		}
	}
	
	/**
	 * 淘宝客佣金返利
	 * @param $order 订单信息
	 * @return bool
	 * @throws \think\exception\PDOException
	 */
	public function changeStauts($order){
		$this->startTrans();
		$recordModel = new CouponCollectRecord();
		try {
			
			//更改淘宝客订单返利状态为待结算
			$tbkRes = Db::name('orderTbk')->where(['id' => $order['id']])
				->update([
					'user_id' => $order['user_id'],
					'record_id' => $order['record_id'],
					'status' => self::STATUS_W
				]);
			if(!$tbkRes) {
				throw new Exception('更改淘宝客订单返利状态出错');
			}
			
			//更改领券记录状态为匹配成功
			$recordRes = $recordModel
				->where(['id' => $order['record_id']])
				->update([
					'status' => $recordModel::STATUS_P
				]);
			if(!$recordRes) {
				throw new Exception('更改领取记录状态出错');
			}
			
			//如果有设置返利规则，且返利金额大于0，进行返利操作
			if(isset($order['rule']) && !empty($order['rule']) && $order['feeString'] > 0) {
				$model = new CommissionRebate();
				$res = $model->addRebateRocord($order['auctionId'], $order['feeString'], $order['user_id'],$order['rule'], $order['taobaoTradeParentId'], RebateRecord::TYPE_TBK, '淘宝客');
				
				if(!$res) {
					throw new Exception('发送奖励出错：'.$model->getError());
				}
			}
			
			
			$this->commit();
			return $order['id'].'更改状态成功'.PHP_EOL;
			
		} catch (Exception $e) {
			$this->rollback();
			return $order['id'].'更改状态出错：'.$e->getMessage().PHP_EOL;
		}
	}
}
